package com.hyh.order.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpStatus;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hyh.feign.clients.CartClient;
import com.hyh.feign.clients.ProductClient;
import com.hyh.feign.clients.UserClient;
import com.hyh.feign.domain.Cart;
import com.hyh.feign.result.PageResult;
import com.hyh.order.dao.OrderMapper;
import com.hyh.order.domain.Orders;
import com.hyh.order.listenner.OrderRedisListener;
import com.hyh.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class OrderServiceImpl  implements OrderService {

    @Autowired
    private CartClient cartClient;

    @Autowired
    private ProductClient productClient;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private OrderRedisListener orderRedisListener;

    @Autowired
    private UserClient userClient;

    // 创建我的订单
    @Override
    public PageResult createOrder(Long id){
        Orders order = getOrders(id);
        // 判断是否有订单
        if(Boolean.TRUE.equals(stringRedisTemplate.hasKey("order:" + order.getUserId() + order.getProductId()))){
            return new PageResult(HttpStatus.HTTP_INTERNAL_ERROR,null,"不可重复下单");
        }
        orderMapper.insert(order);
        // 将订单信息存入到redis
        // 将对象转换为map
        Map<String, Object> orderMap = BeanUtil.beanToMap(order,new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((filedName,filedValue) ->{
                            if(filedValue == null)
                                return null;
                            return filedValue.toString();
                        }));
        // 将map存入redis
        stringRedisTemplate.opsForHash().putAll("order:"+order.getUserId()
                        +order.getProductId(),
                                    orderMap);
        // 设置过期时间删除订单
        orderRedisListener.listenerOrderExpire(order.getUserId(),order.getProductId());
        return new PageResult(HttpStatus.HTTP_OK,order,"创建成功");
    }

    private Orders getOrders(Long id) {
        // 获取购物车信息
        Cart cart = cartClient.getCart(id);
        // 生成19位数的订单号
        Long orderNumber = Long.valueOf(generateUniqueOrderNumber(cart.getUserId()));
        Orders order = new Orders();
        order.setOrderNumber(orderNumber);
        order.setOrderStatus("0");
        order.setOrderTime(new Timestamp(System.currentTimeMillis()+ 8 * 60 * 60 * 1000));
        order.setUserId(cart.getUserId());
        order.setProductId(cart.getProductId());
        order.setProductName(cart.getTitle());
        order.setProductPrice(cart.getPriceTotal());
        order.setPurchaseCount(cart.getCount());
        order.setPayTime(new Timestamp(System.currentTimeMillis()+ 8 * 60 * 60 * 1000));
        return order;
    }


    // 生成唯一订单号
    public String generateUniqueOrderNumber(Integer userId) {
        // 生成时间戳
        long timestamp = System.currentTimeMillis();

        // 生成随机数（在实际应用中可能需要更复杂的逻辑来保证唯一性）
        int randomNum = RandomUtil.randomInt(6); // 生成0-99999之间的随机数

        // 将时间戳和随机数组合成一个19位数的订单号
        return String.format("%d%05d", timestamp, randomNum);
    }
    // 修改订单状态
    @Override
    public PageResult updateOrder(Long id) {
        Orders order = orderMapper.selectById(id);
        order.setOrderStatus("1");
        int i = orderMapper.updateById(order);
        if(i > 0){
            return new PageResult(HttpStatus.HTTP_OK,null,"修改成功");
        }
        return new PageResult(HttpStatus.HTTP_INTERNAL_ERROR,null,"修改失败");
    }

    // 查询所有订单
    @Override
    public PageResult getOrder(String userId,String status){
        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();
        qw.eq(Orders::getOrderStatus,status);
        qw.eq(Orders::getUserId,userId);
        return new PageResult(HttpStatus.HTTP_OK,orderMapper.selectList(qw),"查询成功");
    }

    // 根据订单号查询订单
    @Override
    public Orders getOrderById(Long id) {
        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();
        qw.eq(Orders::getOrderNumber,id);
        return orderMapper.selectOne(qw);
    }

    @Override
    public boolean existOrder(Long id) {
        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();
        qw.eq(Orders::getProductId,id);
        orderMapper.selectList(qw);
        // PageResult userById = userClient.getUserById(1);
        return !orderMapper.selectList(qw).isEmpty();
    }
}
